# encoding=utf8
import sys 
import importlib
import modelft
import time
import random
reload(sys)
sys.setdefaultencoding('utf8')

class MessageAnalysis: #协议解析
    protocol = ""
    mark = ""
    result = []
    def __init__(self):
        pass
    def doGet(self,pro_id,pro_data):
        
        self.protocol = pro_data
        self.mark = pro_id
        model = ModelInit()
        self.result = model.reflection(self.protocol,self.mark) #python反射技术，这里根据消息ID动态导入需要使用的解析对应ID的的库
        #for i in range(len(self.result)):
           #print "i=%d,doget:%s",i,self.result[i]
        #return self.result #list
        self.result.reverse()
        this_time=(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        this_number=str(random.randrange(0,65535))
        self.result.append("本次解析时间：" + this_time + "  解析随机码：" +this_number + '\n \n')
        self.result.reverse()
        return "".join(self.result)#str

class ModelInit:
    header =[]
    result =[]
    protocolStr =""
    revMark = ""
    def __init__(self):
        pass
    def reflection(self,protocol,mark):
        self.protocolStr = protocol
        self.revMark = mark
        if (self.protocolStr.strip() != "" and len(self.protocolStr) > 30 ):
            print "使用808协议分析"
            jT808Message = JT808Message()
            self.protocolStr = jT808Message.getMessageHead(self.protocolStr)#protocolStr  808协议消息体
            header = jT808Message.getResult()# #header 消息头（解析后的结果）
            if (self.revMark =="8900" or self.revMark == "0900"):
                self.protocolStr = jT808Message.getMessageHeadFT(self.protocolStr)
                self.revMark = jT808Message.getMessageID()
                header = jT808Message.getResultFT()
                try:
                    nameJonit='FT_'+self.revMark
                    print(nameJonit)
                    md_Name=importlib.import_module("."+nameJonit,"app.modelft")
                    print(md_Name)
                    cl_Name=getattr(md_Name,nameJonit)#获得类
                    cl_Name_Obj =cl_Name()#实例化对象
                    cl_Name_Obj.LogicAisle(self.protocolStr, header)#调用logicAisle方法
                    self.result = cl_Name_Obj.result #在对象上获取此字段的值
                    for i in range(len(self.result)):
                        print ("ft_reflection:"+self.result[i])
                    return self.result
                except Exception as e:
					#print("file modelft/%s.py is not existed." %nameJonit)
                    print(e)
            else: #如果是JT其他协议，则调用JT_ID.py解析
                try:
                    nameJonit='JT_'+self.revMark
                    print(nameJonit)
                    md_Name=importlib.import_module("."+nameJonit,"app.model808")
                    print(md_Name)
                    cl_Name=getattr(md_Name,nameJonit)#获得类
                    cl_Name_Obj =cl_Name()#实例化对象
                    cl_Name_Obj.LogicAisle(self.protocolStr, header)#调用LogicAisle方法
                    self.result = cl_Name_Obj.result #在对象上获取此字段的值
                    for i in range(len(self.result)):
                        print ("jt_reflection:"+self.result[i])
                    return self.result
                except ImportError:
                    print("file model808/%s.py is not existed." %nameJonit)
                    return self.result.append("输入报文有误，请重新输入")
        else:
            return self.result.append("输入报文有误，请重新输入")

class JT808Message:
    messageType=""#消息类型
    messageAttributes=""#消息体属性
    simNo=""#终端手机号
    messageSerialNo=""#消息流水号
    protocolStr=""#报文
    sign=""
    versionNum=""
    revised=""
    messageID=""#自定义消息ID
    information=["消息ID:", "消息体属性:", "终端手机号:", "终端流水号:"]
    infomationFT=["透传消息类型:", "自定义协议主版本号:", "自定义协议修订号:", "自定义消息ID:"]
    result=[]

    def getMessageHead(self,protocolStr):
        self.protocolStr = protocolStr
        print type(self.protocolStr)
        self.setMessageType(self.protocolStr[2:6])
        self.setMessageAttributes(self.protocolStr[6:10])
        self.setSimNo(self.protocolStr[10:22])
        self.setMessageSerialNo(self.protocolStr[22:26])
        return self.protocolStr[26:len(self.protocolStr)]
    def getResult(self):
        self.result=[]
        for i in range(len(self.information)):
            if (i==0):
                self.result.append(self.information[i] + self.messageType + '\n')
            elif (i==1):
                self.result.append(self.information[i] + self.messageAttributes + '\n')
            elif(i==2):
                self.result.append(self.information[i] + self.simNo + '\n')
            elif(i==3):
                self.result.append(self.information[i] + self.messageSerialNo + "\n")
            else:
                print"getResult"
        return self.result
    def getMessageHeadFT(self,protocolStr):
        self.protocolStr = protocolStr
        self.setSign(protocolStr[0:2])
        self.setVersionNum(protocolStr[2:4])
        self.setRevised(protocolStr[4:6])
        self.setMessageID(protocolStr[6:10])
        return protocolStr[10:len(self.protocolStr)]
    def getResultFT(self):
        for i in range(len(self.infomationFT)):
            if (i==0):
                self.result.append(self.infomationFT[i] + self.sign + '\n')
            elif (i==1):
                self.result.append(self.infomationFT[i] + self.versionNum + '\n')
            elif(i==2):
                self.result.append(self.infomationFT[i] + self.revised + '\n')
            elif(i==3):
                self.result.append(self.infomationFT[i] + self.messageID + '\n')
            else:
                print("getResultFT")
        return self.result
    def getMessageType(self):
        return self.messageType
    def setMessageType(self,messageType):
        self.messageType = messageType
    def getSimNo(self):
        return self.simNo
    def setSimNo(self,simNo):
        self.simNo =simNo
    def getMessageSerialNo(self):
        return self.messageSerialNo
    def setMessageSerialNo(self,messageSerialNo):
        self.messageSerialNo =messageSerialNo
    def getMessageAttributes(self):
        return self.messageAttributes
    def setMessageAttributes(self,messageAttributes):
        self.messageAttributes =messageAttributes
    def getSign(self):
        return self.sign
    def setSign(self,sign):
        self.sign =sign
    def getVersionNum(self):
        return self.versionNum
    def setVersionNum(self,versionNum):
        self.versionNum =versionNum
    def getRevised(self):
        return self.revised
    def setRevised(self,revised):
        self.revised =revised
    def getMessageID(self):
        return self.messageID
    def setMessageID(self,messageID):
        self.messageID =messageID
